import React, { useState } from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import { useDiaryStore } from '../../store/diaryStore';
import { useChartContext } from '../../contexts/ChartContext';

const MOOD_COLORS = {
  'Happy': '#10b981',
  'Sad': '#3b82f6',
  'Excited': '#f59e0b',
  'Anxious': '#ef4444',
  'Calm': '#8b5cf6',
  'Angry': '#dc2626',
  'Grateful': '#059669',
  'Tired': '#6b7280',
  'Motivated': '#f97316',
  'Peaceful': '#84cc16'
};

const MoodDistributionChart: React.FC = () => {
  const getMoodDistribution = useDiaryStore((state) => state.getMoodDistribution);
  const { filters, setFilters } = useChartContext();
  const [hoveredMood, setHoveredMood] = useState<string | null>(null);
  const data = getMoodDistribution();

  if (data.length === 0) {
    return (
      <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
        <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
          Mood Distribution
        </h3>
        <div className="flex items-center justify-center h-64 text-warm-gray-500">
          <p>No mood data available</p>
        </div>
      </div>
    );
  }

  const getColor = (mood: string, index: number) => {
    return MOOD_COLORS[mood as keyof typeof MOOD_COLORS] || `hsl(${(index * 137.5) % 360}, 70%, 50%)`;
  };

  const handleMoodClick = (mood: string) => {
    const isSelected = filters.moods?.includes(mood) || false;
    const newSelectedMoods = isSelected 
      ? filters.moods?.filter(m => m !== mood) || []
      : [...(filters.moods || []), mood];
    
    setFilters({ moods: newSelectedMoods });
  };

  const CustomTooltip = ({ active, payload }: any) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      const isSelected = filters.moods?.includes(data.mood) || false;
      return (
        <div className="bg-white p-3 border border-warm-gray-200 rounded-lg shadow-lg">
          <p className="font-medium text-warm-gray-800">{data.mood}</p>
          <p className="text-sm text-warm-gray-600">
            {data.count} entries ({data.percentage}%)
          </p>
          <p className="text-xs text-blue-600 mt-1">
            {isSelected ? 'Click to remove filter' : 'Click to filter by this mood'}
          </p>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
      <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
        Mood Distribution
      </h3>
      <ResponsiveContainer width="100%" height={300}>
        <PieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            labelLine={false}
            label={({ mood, percentage }) => `${mood} (${percentage}%)`}
            outerRadius={hoveredMood ? 85 : 80}
            fill="#8884d8"
            dataKey="count"
            onClick={(data) => handleMoodClick(data.mood)}
            onMouseEnter={(data) => setHoveredMood(data.mood)}
            onMouseLeave={() => setHoveredMood(null)}
          >
            {data.map((entry, index) => {
              const isSelected = filters.moods?.includes(entry.mood) || false;
              const isHovered = hoveredMood === entry.mood;
              const baseColor = getColor(entry.mood, index);
              const fillColor = isSelected 
                ? baseColor 
                : isHovered 
                  ? baseColor 
                  : `${baseColor}80`; // Add transparency for non-selected
              
              return (
                <Cell 
                  key={`cell-${index}`} 
                  fill={fillColor}
                  stroke={isSelected ? '#374151' : 'none'}
                  strokeWidth={isSelected ? 2 : 0}
                  style={{ cursor: 'pointer' }}
                />
              );
            })}
          </Pie>
          <Tooltip content={<CustomTooltip />} />
        </PieChart>
      </ResponsiveContainer>
      <div className="mt-4">
        {filters.moods && filters.moods.length > 0 && (
          <div className="mb-3 p-2 bg-blue-50 rounded-lg">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-blue-800">
                Filtered by: {filters.moods.join(', ')}
              </span>
              <button
                onClick={() => setFilters({ moods: [] })}
                className="text-xs text-blue-600 hover:text-blue-800 underline"
              >
                Clear
              </button>
            </div>
          </div>
        )}
        <div className="grid grid-cols-2 gap-2 text-sm">
          {data.slice(0, 6).map((entry, index) => {
            const isSelected = filters.moods?.includes(entry.mood) || false;
            return (
              <div 
                key={entry.mood} 
                className={`flex items-center gap-2 p-1 rounded cursor-pointer transition-colors ${
                  isSelected ? 'bg-blue-50' : 'hover:bg-gray-50'
                }`}
                onClick={() => handleMoodClick(entry.mood)}
              >
                <div 
                  className="w-3 h-3 rounded-full" 
                  style={{ backgroundColor: getColor(entry.mood, index) }}
                />
                <span className={`text-warm-gray-700 ${
                  isSelected ? 'font-medium' : ''
                }`}>
                  {entry.mood}: {entry.count}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default MoodDistributionChart;